package com.tdd.api.server.base.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 随机数工具
 */
public class ToolUtils {


    public static DateTimeFormatter dateTimeEC = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

    public static DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static DateTimeFormatter date = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    static String regrexStr = "([\\d]+\\.[\\d]{0,}),([\\d]+\\.[\\d]{0,})";

    public static String getSixRandom() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String appendZero(Integer obj) {
        String lut = obj < 10 ? "0" + obj : String.valueOf(obj);
        return lut;
    }


    public static BigDecimal[] strGisToDecimal(String lng, String lat) {
        BigDecimal lngB = new BigDecimal(lng);
        BigDecimal latB = new BigDecimal(lat);
        return new BigDecimal[]{lngB, latB};
    }

    public static BigDecimal[] strGisToDecimal(String gis) {

        String[] giss = gis.split(",");
        BigDecimal lngB = new BigDecimal(giss[0]);
        BigDecimal latB = new BigDecimal(giss[1]);
        return new BigDecimal[]{lngB, latB};
    }


    public static boolean regrexGisStr(String gisStr) {

        Pattern pattern = Pattern.compile(regrexStr);
        Matcher matcher = pattern.matcher(gisStr);
        return matcher.find();
    }



    public static String asUrlParams(Map<String, String> source) {
        if (CollUtil.isNotEmpty(source)) {
            Iterator<String> it = source.keySet().iterator();
            StringBuilder paramStr = new StringBuilder();
            while (it.hasNext()) {
                String key = it.next();
                if (StrUtil.isBlank(source.get(key))) {
                    continue;
                }
                paramStr.append("&").append(key).append("=").append(source.get(key));
            }
            if (paramStr.length() > 0) {
                // 去掉第一个&
                return paramStr.substring(1);
            }
        }


        return "";


    }


    public static <T> T noNullStringAttr(T cls) {
        Field[] fields = cls.getClass().getDeclaredFields();
        if (fields == null || fields.length == 0) {
            return cls;
        }
        for (Field field : fields) {
            if ("String".equals(field.getType().getSimpleName())) {
                field.setAccessible(true);
                try {
                    Object value = field.get(cls);
                    if (value == null) {
                        field.set(cls, "");
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return cls;
    }

    /**
     * 生成随机密码生成方式一
     * 密码字典 -> 随机获取字符
     *
     * @param len 生成密码长度（最短为4位）
     * @return 随机密码
     */
    public static String getRandomCode(int len) {
        // 如果len 小于等于3
        //生成的随机数
        int i;
        //生成的密码的长度
        int count = 0;
        // 密码字典
        char[] str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        // 大写字母密码字典
        List<Character> bigStrList = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        Set<Character> bigStrSet = new HashSet<>(bigStrList);
        // 小写字母的密码字典
        List<Character> upperStrList = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
        Set<Character> upperStrSet = new HashSet<>(upperStrList);
        // 数字的密码字典
        List<Character> numStrList = Arrays.asList('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        Set<Character> numStrSet = new HashSet<>(numStrList);

        StringBuilder builder = new StringBuilder();
        Random r = new Random();
        boolean isContainBigChar = false;
        boolean isContainUpperChar = false;
        boolean isContainNumChar = false;
        while (count < len - 3) {
            //生成 0 ~ 密码字典-1之间的随机数
            i = r.nextInt(str.length);
            builder.append(str[i]);
            count++;
            if (!isContainBigChar && bigStrSet.contains(str[i])) {
                isContainBigChar = true;
            }
            if (!isContainUpperChar && upperStrSet.contains(str[i])) {
                isContainUpperChar = true;
            }
            if (!isContainNumChar && numStrSet.contains(str[i])) {
                isContainNumChar = true;
            }
        }
        // 如果不存在的，则加，确保一定会存在数字，大写字母，小写字母
        if (!isContainBigChar) {
            builder.append(bigStrList.get(r.nextInt(bigStrList.size())));
        }
        if (!isContainUpperChar) {
            builder.append(upperStrList.get(r.nextInt(upperStrList.size())));
        }
        if (!isContainNumChar) {
            builder.append(numStrList.get(r.nextInt(numStrList.size())));
        }
        while (builder.length() < len) {
            builder.append(str[r.nextInt(str.length)]);
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        System.out.println(getSixRandom());
    }
}
